﻿
//------------------------------------------------ปรับปรุง ค่าใน Element ใช้วิธี Ajax
//options.url- options.url ที่จะไป get data
//dataJson - ข้อมูลที่จะส่งเข้าไป เป็นแบบ Json
//SelectorElement - dropdownlist 
(function ($) {
    $.fn.AjexUpdateDataInElement = function (settings) {
        var holder = $(this);
        var defaults = {
            url: "",
            data: "",
            selectorOfElement: "",
            onChange: "",
            callBack: "",
            isMuti:false,
            isGetDataFromEl:false,
        }
        var options = jQuery.extend(defaults, settings);
        ///-------------------------
        if (holder.is("select")) {
            holder.html("<option>loading..</option>");
        }

        if(options.isGetDataFromEl == false){
           GetDataFromServer(holder,options);
        }else{
           $(holder).find("select.isGetDataFromEl").each(function(){
                GetDataFromClient($(this),options);
           });
           $(holder).find("div.isGetDataFromEl").each(function(){
                //MutiSelectFromClient($(this),options);
                //$(this).MultiSelect(options);
                $(this).jMultiSelect('initial',options);
           });
        }
        function GetDataFromClient(holder,options)
        {
            var obj = $(holder).next("input.selectListData").val();
            var jsonData = null;
            try{
                jsonData = jQuery.parseJSON(obj);
            }catch(e){
                console.log(e.toString());
            }
            //alert(jsonData.toSource());
            if(jsonData == null)
            {
                return false;
            }
            //ลบ option ของเดิ่ม
            holder.find("option").empty();
            //วาด option เป็นใน string
            var strHtml = "";
            var isSelected = false;
            try{
                var selectedvalue = $.trim($(holder).attr("value1"));
                if(selectedvalue == "")
                {
                    selectedvalue = jsonData.Selected;
                }
            }
            catch(e)
            {
                var selectedvalue = "";
            }
            console.log(jsonData.toString());                   
            $.each(jsonData.listItem, function (i) {
                //ตรวจสอบ selected
                if (selectedvalue == jsonData.listItem[i].value) {
                    strHtml += "<option style='" + jsonData.listItem[i].css + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 + "' title='" + jsonData.listItem[i].title + "'   selected >" + jsonData.listItem[i].text + "</option>";
                    isSelected = true;
                }
                else {
                    strHtml += "<option style='" + jsonData.listItem[i].css + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 + "' title='" + jsonData.listItem[i].title + "' >" + jsonData.listItem[i].text + "</option>";
                    
                }
            });
            holder.html(strHtml);

            if(options.isMuti == false){
                if ($.trim(jsonData.Selected) != "" && $.trim(jsonData.Selected) != 0 && isSelected == false) {
                    holder.find("option:selected").text("No Reference Data");
                }
                if ($(holder).attr("onChange") != "") {
                    holder.unbind('change');
                    holder.change(function () {
                        eval($(holder).attr("onChange"))($(holder));
                    });
                }
                if (holder.hasClass("disableControl") == true) {
                    holder.hide();
                    var labelShow = "";
                    var temp = holder.find("option:selected").val()

                    if (temp != "" && temp != null) {
                        labelShow = holder.find("option:selected").text()
                    }
                    holder.after('<input type="text" value="' + labelShow + '" class="input-readOnly tempControl" readOnly="readOnly" style="width:' + holder.css("width") + '" >');
                }
            }else{
                $(holder).each(function(){
                    $(this).html(strHtml);
                    var key = $(this).attr("value1");
                    $(this).val(key);
                    if ($.trim(jsonData.Selected) != "" && $.trim(jsonData.Selected) != 0 && isSelected == false) {
                        $(this).find("option:selected").text("No Reference Data");
                    }
                    if (options.onChange != "") {
                        $(this).unbind('change');
                        $(this).change(function () {
                            eval(options.onChange)($(this));
                        });
                    }
                    if ($(this).hasClass("disableControl") == true) {
                        $(this).hide();
                        var labelShow = "";
                        var temp = $(this).find("option:selected").val()

                        if (temp != "" && temp != null) {
                            labelShow = $(this).find("option:selected").text()
                        }
                        $(this).after('<input type="text" value="' + labelShow + '" class="input-readOnly tempControl" readOnly="readOnly" style="width:' + $(this).css("width") + '" >');
                    }
                });
            }//endif isMuti
            if ($(holder).attr("callBack") != "") {
                try {
                    eval($(holder).attr("callBack"))($(holder));
                }
                catch (err) {
                    alert("javaScript Ex:AjexUpdateDataInElement CallBack Name=" + $(holder).attr("callBack") + " msg=" + err);
                }
            }
        }//end GetDataFromClient
        ///-------------------------
        function GetDataFromServer(holder,options)
        {
            $.getJSON(options.url + "?ts=" + new Date().getTime(), options.data, function (jsonData) {
            //select ให้ทำ
            if (holder.is("select")) {
                //ลบ option ของเดิ่ม
                holder.find("option").empty();
                //วาด option เป็นใน string
                var strHtml = "";
                var isSelected = false;
                $.each(jsonData.listItem, function (i) {

                    //ตรวจสอบ selected
                    if (jsonData.Selected == jsonData.listItem[i].value) {
                        strHtml += "<option style='" + jsonData.listItem[i].css + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 + "'  title='" + jsonData.listItem[i].Title + "' selected >" + jsonData.listItem[i].text + "</option>";
                        isSelected = true;
                    }
                    else {
                        strHtml += "<option style='" + jsonData.listItem[i].css + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 + "' title='" + jsonData.listItem[i].Title + "' >" + jsonData.listItem[i].text + "</option>";
                    }
                });
                    if(options.isMuti == false){
                        holder.html(strHtml);
                        if ($.trim(jsonData.Selected) != "" && $.trim(jsonData.Selected) != 0 && isSelected == false) {
                            holder.find("option:selected").text("No Reference Data");
                        }
                        if (options.onChange != "") {
                            holder.unbind('change');
                            holder.change(function () {
                                eval(options.onChange)($(holder));
                            });
                        }
                        if (holder.hasClass("disableControl") == true && $(holder).next(".tempControl").size() == 0) {
                            holder.hide();
                            var labelShow = "";
                            var temp = holder.find("option:selected").val()

                            if (temp != "" && temp != null) {
                                labelShow = holder.find("option:selected").text()
                            }
                            holder.after('<input type="text" value="' + labelShow + '" class="input-readOnly tempControl" readOnly="readOnly" style="width:' + holder.css("width") + '" >');
                        }
                    }else{
                        $(holder).each(function(){
                            $(this).html(strHtml);
                            var key = $(this).attr("value1");
                            $(this).val(key);
                            if ($.trim(jsonData.Selected) != "" && $.trim(jsonData.Selected) != 0 && isSelected == false) {
                                $(this).find("option:selected").text("No Reference Data");
                            }
                            if (options.onChange != "") {
                                $(this).unbind('change');
                                $(this).change(function () {
                                    eval(options.onChange)($(this));
                                });
                            }
                            if ($(this).hasClass("disableControl") == true && $(this).next(".tempControl").size() == 0) {
                                $(this).hide();
                                var labelShow = "";
                                var temp = $(this).find("option:selected").val()

                                if (temp != "" && temp != null) {
                                    labelShow = $(this).find("option:selected").text()
                                }
                                $(this).after('<input type="text" value="' + labelShow + '" class="input-readOnly tempControl" readOnly="readOnly" style="width:' + $(this).css("width") + '" >');
                            }
                        });
                    }
                }
                else if (holder.is("input")) {
                    //                $.each(jsonData.listItem, function (i) {
                    //                    //ตรวจสอบ selected
                    //                    if (jsonData.Selected == jsonData.listItem[i].value) {
                    //                        strHtml += "<input type=\"text\" value=\"" + jsonData.listItem[i].value2 + "\" value1='" + jsonData.listItem[i].value1 + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 + "'>";
                    //                        holder.html(strHtml);
                    //                    }
                    //                });
                }

                //call back
                if (options.callBack != "") {
                    try {
                        eval(options.callBack)($(holder));
                    }
                    catch (err) {
                        alert("javaScript Ex:AjexUpdateDataInElement CallBack Name=" + options.callBack + " msg=" + err);
                    }

                }
            });
        }//end function GetData FromServer
//end plugin
    };
})(jQuery);


(function ($) {
    var methods = {
        initial: function (options) {
            var holder = $(this);
            var obj = $(holder).next("input.selectListData").val();
            if(obj != ""){
                MutiSelectFromClient(holder,options);
            }else{
                
            }
        },
        serializeToInput: function (options) {
           
        },
        clear: function (isUseDefaultVal) {
           var holder = $(this);
           clearvalue(holder,isUseDefaultVal);
        },
        disable: function () {
            var holder = $(this);
            disable(holder);
        },
        enable: function () {
            var holder = $(this);
            enable(holder);
        }
    };

    $.fn.jMultiSelect = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.jButton');
        }
    };
    
    function MutiSelectFromClient(holder,options)
    {
        var obj = $(holder).next("input.selectListData").val();
        var jsonData = jQuery.parseJSON(obj);
        //alert(jsonData.listItem[0].value);
        var width = holder.width();
        var isSelected = false;
        try{
            var selectedvalue = $.trim($(holder).attr("value1"));
            if(selectedvalue == "")
            {
                selectedvalue = jsonData.Selected;
            }
        }
        catch(e)
        {
            var selectedvalue = "";
        }
        var controlHtml ="";
        var optionHtml = "";
        $.each(jsonData.listItem, function (i) {
            //ตรวจสอบ selected
            if(jsonData.listItem[i].Class == "pleaseselect"){

            }else{
            optionHtml += "<li><label class='captionMSlist' style='width:100%' caption='"+jsonData.listItem[i].text+"'>";
                var text2 = (jsonData.listItem[i].text2 != null && jsonData.listItem[i].text2 != "") ? " | "+jsonData.listItem[i].text2  : "";
                var image = (jsonData.listItem[i].Image != null && jsonData.listItem[i].Image != "") ? " | <img src='"+jsonData.listItem[i].Image+"' />" : "";
                if (selectedvalue == jsonData.listItem[i].value) {
                    optionHtml += "<input class='mscb " + jsonData.listItem[i].Class + "' type='checkbox' style='" + jsonData.listItem[i].css 
                    + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 
                    + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 
                    + "' title='" + jsonData.listItem[i].Title + "' defaultval='"+jsonData.listItem[i].Checked +"' " + jsonData.listItem[i].Checked + " />" 
                    + jsonData.listItem[i].text + image + text2 +"";
                }
                else
                {
                    optionHtml += "<input class='mscb " + jsonData.listItem[i].Class + "' type='checkbox' style='" + jsonData.listItem[i].css 
                    + "' value='" + jsonData.listItem[i].value + "' value1='" + jsonData.listItem[i].value1 
                    + "' value2='" + jsonData.listItem[i].value2 + "' value3='" + jsonData.listItem[i].value3 
                    + "' title='" + jsonData.listItem[i].Title + "' defaultval='"+jsonData.listItem[i].Checked +"' " + jsonData.listItem[i].Checked + " / >" 
                    + jsonData.listItem[i].text + image + text2 +"";
                }
            optionHtml += "</label></li>";
            }
        });
            
        controlHtml = "<div style='display:none;' class='ms-drop bottom'><ul style='max-height:250px;width:95%'>" + optionHtml + "</ul></div>";
        //controlHtml = "<button type='button' class='ms-choice' style='width:"+width+"px;'><input type='text' class='captionMSHead' readOnly='readOnly'><div class='open'></div></button>" + controlHtml;
        controlHtml = "<button type='ui-require-field' class='ms-choice' style='width:"+width+"px;'><input type='text' class='captionMSHead' readOnly='readOnly'><div class='open'></div></button>" + controlHtml;
        holder.html(controlHtml); 
        MutiSelectEvent(holder); 
    }
    function MutiSelectEvent(holder)
    {
        CheckSelectAll(holder);
        //checked Default
        SetCaption(holder);
        makevalueHidden(holder);
        
        EventMschoice(holder);
        //click selectall 
        $(holder).find("input.selectall").click(function(){
            if($(this).attr("checked") == "checked"){
                $(holder).find("input.mscb").each(function(){
                    $(this).attr("checked","checked");
                });
                $(holder).find(".ms-choice").find(".captionMSHead").val($(this).parent().text());
            }else{
                $(holder).find("input.mscb").each(function(){
                    $(this).removeAttr("checked");
                });
                SetCaption(holder);
            }
            makevalueHidden(holder);
        });
        //เมื่อ click checkbox ทั้งหมด ยกเว้น selectall ให้ set caption on header
        $(holder).find("input:checkbox:not(.selectall)").click(function(){
            SetCaption(holder);
            makevalueHidden(holder);
        });
        //เมื่อ mousup จะ clear lost focus และ set focus ใหม่
        $(holder).mouseup(function() {
            $(holder).focus();
            var timers=$("body").data("timeOut");
            for (var i = 0; i < timers.length; i++)
            {
                clearTimeout(timers[i]);
            }
        });
        // เมื่อ คลิกนอก dropdown จะปิด list dropdown
        var timers = new Array();
        $("body").data("timeOut",timers);
        $(holder).focusout(function (){
            //var hasFocus = $(holder).is(':focus'); 
            var delayID = setTimeout(function () {
                $(holder).find(".ms-drop").css("display","none");
                check_require_field(holder);
            }, 400);
            var timers=$("body").data("timeOut");
            timers.push(delayID);
            $("body").data("timeOut",timers);
        });

        $(holder).find("ul").click(function(event){
            event.stopPropagation();
        });

    }
    function check_require_field(holder)
    {
        if($(holder).hasClass("ui-require-field"))
        {
            if($(holder).find(".captionMSHead").val() == ""){
                $(holder).nextAll("div.validateMes:first").remove().end()
                .after('<div class="validateMes ui-state-highlight ui-helper-clearfix"  style="padding:4px;min-width:' 
                + ($(holder).width() + 20) + 'px;left:'+$(holder).position().left
                +'px;top:'+($(holder).position().top+28)+'px;"><div class="ui-icon ui-icon-info" style="float:left"></div><div class="valMes" style="float:left">Please Select</div><span class="btnCloseValidateMes">x<span></div>');
                 CloseValidateMes();
             }
        }
    }
    function CloseValidateMes() {
        $(".btnCloseValidateMes").click(function () {
            $(this).parents(".validateMes").remove();
        });
    }

    function EventMschoice(holder)
    {
        //click แล้วเปิด list
        $(holder).find(".ms-choice:first").unbind("click");
        $(holder).find(".ms-choice:first").bind("click",function(){
            //$(".ms-drop").css("display","none");
            if($(this).next(".ms-drop").css("display") == "none"){
                $(this).next(".ms-drop").css("display","block");
                 $(holder).focus();
            }else{
                $(this).next(".ms-drop").css("display","none");
            }
        });
    }
    function GetCaptionStr(holder)
    {
        var result ="";
        //check lost select
        var coutTotal=$(holder).find("input.mscb:not(.selectall)").size();
        var coutChecked=$(holder).find("input.mscb:checked:not(.selectall)").size();
        //alert(coutTotal + ","+ coutChecked);
        //alert($(holder).find(":checkbox.selectall").size());
        if($(holder).find(":checkbox.selectall").size() > 0 && coutTotal == coutChecked)
        {
            $(holder).find("input.selectall").attr("checked","checked");
            result=$(holder).find("input.selectall").parent().attr("caption");
        }else{
            $(holder).find("input.selectall").removeAttr("checked");
            $(holder).find("input.mscb:checked").each(function(){
                if(result =="")
                {
                    result += $(this).parent().attr("caption");
                }else{
                    result += "," + $(this).parent().attr("caption");
                }
            });
            //alert(result);
        }
        return result;
    }
    function CheckSelectAll(holder)
    {
        if($(holder).find("input.selectall").attr("checked")=="checked")
        {
            $(holder).find("input.mscb").each(function(){
                $(this).attr("checked","checked");
            });
            $(holder).find(".ms-choice").find(".captionMSHead").val($(this).parent().text());
        }
           
    }
    function SetCaption(holder)
    {
        var strCaption=GetCaptionStr(holder);
        $(holder).find(".ms-choice").find(".captionMSHead").val(strCaption);
    }

    function makevalueHidden(holder)
    {
        var attName = $(holder).attr("name");
        var i=0;
        $(holder).find("input.mscb:not(.selectall)").each(function(){
            $(this).parent().find(".ms-value-hidden").next("span").remove(); //[TODO]
            $(this).parent().find(".ms-value-hidden").remove();
            if($(this).attr("checked") == "checked")
            {
                try{
                    if (attName != undefined && attName.search("[y]") != -1) {
                        var name = attName.replace("[y]","["+i+"]");
                    }
                }
                catch(e)
                {
                    alert(e);
                }
                var str = "<input type='hidden' class='ms-value-hidden' name='"+name+"' value='"+$(this).val()+"'><span>.<span>"; //[TODO] <span>.<span>
                $(this).parent().append(str);
                i++;
            }
        });
    }
    function clearvalue(holder,isUseDefaultVal)
    {
        if($(holder).hasClass("multiSelect"))
        {
            if(isUseDefaultVal == true)
            {
                clearDefault(holder);
            }else{
                clearAll(holder);
            }
        }else{
            if(isUseDefaultVal == true)
            {
                $(holder).find(".multiSelect").each(function(){
                    clearDefault(this);
                });
            }else{
                $(holder).find(".multiSelect").each(function(){
                    clearAll(this);
                });     
            }
        }
    }
    function clearDefault(holder)
    {
        $(holder).find("input.mscb").each(function(){
            
            if($(this).attr("defaultval") == "checked"){
                $(this).attr("checked","checked");
                SetCaption(holder);
            }else{
                $(this).parent(".captionMSlist:first").find(".ms-value-hidden").next("span").remove(); //[TODO]
                $(this).parent(".captionMSlist:first").find(".ms-value-hidden").remove();
                $(this).removeAttr("checked");
                SetCaption(holder);
            }
        });
        makevalueHidden(holder);
    }
    function clearAll(holder)
    {
        $(holder).find("input.mscb").each(function(){
            $(this).parent(".captionMSlist:first").find(".ms-value-hidden").next("span").remove(); //[TODO]
            $(this).parent(".captionMSlist:first").find(".ms-value-hidden").remove();
            $(this).removeAttr("checked");
            SetCaption(holder);
        });
        makevalueHidden(holder);
    }

    function disable(holder)
    {
        $(holder).find(".ms-choice").off();
        $(holder).find(".ms-choice").addClass("ms-disable");
    }
    function enable(holder)
    {
        $(holder).find(".ms-choice").removeClass("ms-disable");
        EventMschoice(holder);
        
    }


    //end plugin
})(jQuery);














